package cn.magicman.demo;

import java.util.concurrent.*;

public class ThreadPoolDemo {
    public static void main(String[] args) throws Exception {

        /*ExecutorService pool = new ThreadPoolExecutor(
                5,                                     // 核心线程数 (常驻线程)
                10,                                    // 最大线程数 (突发流量时扩容)
                60L, TimeUnit.SECONDS,                 // 空闲线程超时时间
                new LinkedBlockingQueue<>(100),        // 有界队列（防止OOM）
                new ThreadPoolExecutor.AbortPolicy()    // 拒绝策略（直接抛出RejectedExecutionException）
        );*/

//        ExecutorService pool = Executors.newSingleThreadExecutor();

//        ExecutorService pool = Executors.newFixedThreadPool(2);

        // 守护线程池（任务不会阻止JVM退出）
        /*ExecutorService daemonPool = Executors.newFixedThreadPool(3, r -> {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        });*/


        ExecutorService pool = Executors.newFixedThreadPool(3);

        Callable<String> task = () -> {
            return ExcuteTask();
        };

        Future<String> result = pool.submit(task);

        Thread.sleep(5000);
        if (result.isDone()) {
            System.out.println("执行完毕");
        } else {
            System.out.println("还在执行");
        }
        pool.shutdown();
    }


    private static String ExcuteTask() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "正在执行任务" + i);
//            Thread.sleep(1000);
        }
        return "任务执行完毕！";
    }
}